package com.tarzan.mybatis.config;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import com.tarzan.common.core.utils.Parse;
import com.tarzan.common.core.utils.PropUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Package com.tarzan.mybatis.config
 * @Title DruidConfiguration
 * @Description TODO
 * @Author liujinshan
 * @CreateTime 2021/7/19 15:51
 */

@Configuration
public class DruidConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

    @Bean
    public DruidDataSource druidDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(PropUtil.getInstance().getConfig("spring.datasource.url", PropUtil.PUBLIC_CONF_JDBC));
        dataSource.setUsername(PropUtil.getInstance().getConfig("spring.datasource.username", PropUtil.PUBLIC_CONF_JDBC));
        dataSource.setPassword(PropUtil.getInstance().getConfig("spring.datasource.password", PropUtil.PUBLIC_CONF_JDBC));
        dataSource.setDriverClassName(PropUtil.getInstance().getConfig("spring.datasource.driver-class-name", PropUtil.PUBLIC_CONF_JDBC));
        //初始化大小，最小，最大
        dataSource.setInitialSize(Parse.toInt(PropUtil.getInstance().getConfig("spring.datasource.initialSize", PropUtil.PUBLIC_CONF_JDBC)));
        dataSource.setMinIdle(Parse.toInt(PropUtil.getInstance().getConfig("spring.datasource.minIdle", PropUtil.PUBLIC_CONF_JDBC)));
        dataSource.setMaxActive(Parse.toInt(PropUtil.getInstance().getConfig("spring.datasource.maxActive", PropUtil.PUBLIC_CONF_JDBC)));
        //配置获取连接等待超时的时间
        dataSource.setMaxWait(Parse.toLong(PropUtil.getInstance().getConfig("spring.datasource.maxWait", PropUtil.PUBLIC_CONF_JDBC)));
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        dataSource.setTimeBetweenEvictionRunsMillis(Parse.toLong(PropUtil.getInstance().getConfig("spring.datasource.timeBetweenEvictionRunsMillis", PropUtil.PUBLIC_CONF_JDBC)));
        //配置一个连接在池中最小生存的时间，单位是毫秒
        dataSource.setMinEvictableIdleTimeMillis(Parse.toLong(PropUtil.getInstance().getConfig("spring.datasource.minEvictableIdleTimeMillis", PropUtil.PUBLIC_CONF_JDBC)));
        dataSource.setValidationQuery(PropUtil.getInstance().getConfig("spring.datasource.validationQuery", PropUtil.PUBLIC_CONF_JDBC));
        dataSource.setTestWhileIdle(Parse.toBoolean(PropUtil.getInstance().getConfig("spring.datasource.testWhileIdle", PropUtil.PUBLIC_CONF_JDBC)));
        dataSource.setTestOnBorrow(Parse.toBoolean(PropUtil.getInstance().getConfig("spring.datasource.testOnBorrow", PropUtil.PUBLIC_CONF_JDBC)));
        dataSource.setTestOnReturn(Parse.toBoolean(PropUtil.getInstance().getConfig("spring.datasource.testOnReturn", PropUtil.PUBLIC_CONF_JDBC)));
        //打开PSCache，并且指定每个连接上PSCache的大小
        dataSource.setPoolPreparedStatements(Parse.toBoolean(PropUtil.getInstance().getConfig("spring.datasource.poolPreparedStatements", PropUtil.PUBLIC_CONF_JDBC)));
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(Parse.toInt(PropUtil.getInstance().getConfig("spring.datasource.maxPoolPreparedStatementPerConnectionSize", PropUtil.PUBLIC_CONF_JDBC)));
        WallConfig wallConfig = new WallConfig();

//        wallConfig.setCreateFunctionAllow(true);
        wallConfig.setMultiStatementAllow(true);
        wallConfig.setSetAllow(true);

        WallFilter wallFilter = new WallFilter();
        wallFilter.setConfig(wallConfig);
        List<Filter> filters = new ArrayList<>();
        filters.add(wallFilter);
        dataSource.setProxyFilters(filters);
        try {
            //配置监控统计拦截的filters，去掉后监控界面sql无法统计，'wall'用于防火墙
            dataSource.setFilters(PropUtil.getInstance().getConfig("spring.datasource.filters", PropUtil.PUBLIC_CONF_JDBC));
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        return dataSource;
    }

    /**
     * @title DruidStatViewServle
     * @description TODO 注册一个StatViewServlet
     * @param
     * @return org.springframework.boot.web.servlet.ServletRegistrationBean
     * @author liujinshan
     * @data 2021/7/20 8:19
     */
    @Bean
    public ServletRegistrationBean DruidStatViewServle(){

        //org.springframework.boot.context.embedded.ServletRegistrationBean提供类的进行注册.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

        //添加初始化参数：initParams

        //白名单：
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");

        //IP黑名单 (存在共同时，deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.0.114");

        //登录查看信息的账号密码.
        servletRegistrationBean.addInitParameter("loginUsername","admin");
        servletRegistrationBean.addInitParameter("loginPassword","123456");

        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }

    /**
     * @title druidStatFilter
     * @description TODO 注册一个：filterRegistrationBean
     * @param
     * @return org.springframework.boot.web.servlet.FilterRegistrationBean
     * @author liujinshan
     * @data 2021/7/20 8:19
     */
    @Bean
    public FilterRegistrationBean druidStatFilter(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());

        //添加过滤规则.
        filterRegistrationBean.addUrlPatterns("/*");

        //添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

        return filterRegistrationBean;
    }
}
